# -*- coding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
from openerp import SUPERUSER_ID

class user_share_rel(osv.osv):
    _name = "user.share.rel"
    # 用户共享 字段的共享表 （中间表）
    # 给这个表创建 tree表充分的有利于手动的维护

    def create(self, cr, uid, vals, context=None):
        # all_user_ids = []
        # for res_user in self.pool.get("res.users").browse(cr, uid, vals.get('dest_id'), context=context):
        #     all_user_ids.append(res_user.share_to_ids)
        # print all_user_ids
        return super(user_share_rel, self).create(cr, uid, vals, context=context)

    _columns = {
        'dest_id': fields.many2one("res.users", string="分享给", required=True),
        'source_id': fields.many2one("res.users", string="被分享", required=True),
    }
    # 设置 提醒如果已经分享给这个用户自己的销售订单或者相关的记录
    _sql_constraints = [
        ('code_apply_uniq', 'unique(dest_id,source_id)', '此用户已经分享过了!')
    ]


class res_users(osv.osv):
    _inherit = "res.users"
    # 继承 用户，设置 共享字段  many2many字段 中间表是一个实体的表
    # 本来是系统会直接新建一个 简单的表 不用odoo 的class 但是不利于手动的维护所以 要进行 新建实体表 方便维护
    _decription = 'add Superior subordinate relationship function'

    def _compute_customers_receivable(self, cr, uid, ids, name, arg, context=None):
        res={}
        partner_obj = self.pool.get('res.partner')
        for user in self.browse(cr,uid,ids,context=context):
            credit_sum = 0
            partner_id = partner_obj.search(cr,uid,[('user_id','=',user.id)],context=context)
            for partner in partner_obj.browse(cr,uid,partner_id,context=context):
                credit_sum += partner.credit
            res[user.id] = credit_sum
        return res

    def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        # 當搜索销售订单的时候进行 一系列操作 ，返回的符合条件的结果
        args = args or []
        if self.has_group(cr, uid, 'dftg_ext.sale_deputy_manager') and not\
            self.has_group(cr, uid, 'base.group_sale_manager') and context.get('deputy_manager_cant'):
            model_data_obj = self.pool.get('ir.model.data')
            card_exchange_order_id = model_data_obj.xmlid_to_res_id(
                cr, SUPERUSER_ID, 'base.group_sale_manager')
            args.append(['groups_id', 'not in', card_exchange_order_id])
        super_list = super(res_users, self).name_search(cr, uid, name, args,
                                                               operator=operator, context=context, limit=limit)
        return super_list

    def create(self, cr, uid, vals, context=None):
        return_vals = super(res_users, self).create(cr, uid, vals, context=context)
        employee_obj = self.pool.get('hr.employee')
        if vals.get('partner_id'):
            employee_id = employee_obj.search(cr, uid, [('address_home_id', '=',
                                                       vals.get('partner_id'))], context=context)
            if employee_id:
                employee_obj.write(cr, uid, employee_id, {'user_id': return_vals}, context=context)

        return return_vals

    _columns = {
        'share_to_ids': fields.many2many('res.users', "user_share_rel", 'source_id', 'dest_id', string="共享给"),
        'point_balance': fields.related('partner_id', 'point_balance', type='integer', string='我的积分'),
        'customers_receivable':fields.function(_compute_customers_receivable,string='客户应收款合计',type='float',readonly=True)
    }

class access_log(osv.osv):
    _name = 'access.log'
    _columns = {
        "user_id": fields.many2one('res.users', u'访问人'),
        "access_model": fields.char(u'访问模型'),
        "context": fields.text(u'访问情况上下文'),
        "record_id": fields.char(u'记录ID'),
        "other_info": fields.text(u'其他信息')
    }